<template>
<div class="grid-searchbar clearfix">
	<el-form :model="searchbarForm" :inline="true" ref="searchbarForm" @submit.native.prevent>
		<template v-for="(item,index) in searchItems.normal">
			<el-form-item :prop="item.field" :label="item.name+' '" :key="item.field+index">
				<el-input v-if="item.type=='text'" :size="size" @keyup.enter.native="searchHandle()"
					v-model="searchbarForm[item.field]" :placeholder="'请输入'+item.name"></el-input>
				<el-input v-else-if="item.type=='number'" type="number" :size="size" @keyup.enter.native="searchHandle()"
					v-model="searchbarForm[item.field]" :placeholder="'请输入'+item.name"></el-input>
				<el-select v-else-if="item.type=='select'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]" :placeholder="'请选择'+item.name">
					<el-option v-for="op in item.options" :key="op.value" :label="op.label" :value="op.value"></el-option>
				</el-select>
				<el-date-picker v-else-if="item.type=='date' || item.type=='week' || item.type=='month' || item.type=='year'" 
					:type="item.type" :size="size" @change="searchHandle()"
					:value-format="item.valueFormat"
					v-model="searchbarForm[item.field]" :placeholder="'请选择'+item.name"></el-date-picker>
				<el-date-picker v-else-if="item.type=='daterange'" type="daterange" :size="size" @change="searchHandle()"
					:value-format="item.valueFormat" :default-time="['00:00:00', '23:59:59']"
					range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
					v-model="searchbarForm[item.field]" :placeholder="'请选择'+item.name"></el-date-picker>
				<el-radio-group v-else-if="item.type=='radio'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]">
					<el-radio-button v-for="op in item.options" :key="op.value" :label="op.value">{{op.label}}</el-radio-button>
				</el-radio-group>
				<el-checkbox-group v-else-if="item.type=='checkbox'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]">
					<el-checkbox-button v-for="op in item.options" :key="op.value" :label="op.value">{{op.label}}</el-checkbox-button>
				</el-checkbox-group>
			</el-form-item>	
		</template>
		<template v-if="searchItems.more">
		<span v-for="(item,index) in searchItems.more" :key="item.field+index" v-show="!showMoreFlag">
			<el-form-item :prop="item.field" :label="item.name+' '" :key="item.field+index">
				<el-input v-if="item.type=='text'" :size="size" @keyup.enter.native="searchHandle()"
					v-model="searchbarForm[item.field]" :placeholder="'请输入'+item.name"></el-input>
				<el-input v-else-if="item.type=='number'" type="number" :size="size" @keyup.enter.native="searchHandle()"
					v-model="searchbarForm[item.field]" :placeholder="'请输入'+item.name"></el-input>
				<el-select v-else-if="item.type=='select'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]" :placeholder="'请选择'+item.name">
					<el-option v-for="op in item.options" :key="op.value" :label="op.label" :value="op.value"></el-option>
				</el-select>
				<el-date-picker v-else-if="item.type=='date' || item.type=='week' || item.type=='month' || item.type=='year'" 
					:type="item.type" :size="size" @change="searchHandle()"
					:value-format="item.valueFormat"
					v-model="searchbarForm[item.field]" :placeholder="'请选择'+item.name"></el-date-picker>
				<el-date-picker v-else-if="item.type=='daterange'" type="daterange" :size="size" @change="searchHandle()"
					:value-format="item.valueFormat" :default-time="['00:00:00', '23:59:59']"
					range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
					v-model="searchbarForm[item.field]" :placeholder="'请选择'+item.name"></el-date-picker>
				<el-radio-group v-else-if="item.type=='radio'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]">
					<el-radio-button v-for="op in item.options" :key="op.value" :label="op.value">{{op.label}}</el-radio-button>
				</el-radio-group>
				<el-checkbox-group v-else-if="item.type=='checkbox'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]">
					<el-checkbox-button v-for="op in item.options" :key="op.value" :label="op.value">{{op.label}}</el-checkbox-button>
				</el-checkbox-group>
				<!-- 省市区 -->
				<el-cascader v-else-if="item.type=='region'" :size="size" @change="searchHandle()"
					v-model="searchbarForm[item.field]" filterable
					:options="regionOptions"
					:props="cascaderProps" clearable
				></el-cascader>
			</el-form-item>	
		</span>
		</template>
		<div style="float:right;line-height: 40px;">
			<a class="show-more-btn" href="javascript:void(0)" @click="showMoreHandle" v-if="searchItems.more && searchItems.more.length>0">
				<span v-if="showMoreFlag">更多<span class="triangle-down"></span></span>
				<span v-else>收起<span class="triangle-up"></span></span>
			</a>
			<el-button type="success" icon="el-icon-search" :size="size" @click="searchHandle()">查询</el-button>
			<el-button icon="el-icon-delete" :size="size" @click="clearSearchHandle">重置</el-button>
		</div>
	</el-form>
</div>
</template>

<script>
import { regionData } from '@/utils/globalData'
import * as Tool from '@/utils/tool'
export default {
	name: 'Searchbar',
	props: {
		// 表单元素大小
		size:{
			type:String,
			default:'small'
		},
		searchItems:{
			type:Object,
			default(){
				return {
					'normal':[],			// 常规搜索
					'more':[]				// 隐藏搜索
				}
			}
		},
		pagination:{						// table的分页数据，用于点击搜索是url带上分页数据
			type:Object,
			default(){
				return {
					total: 0,
					page: 1,
					limit: 20
				}
			}
		}
	},
	data(){
		return {
			showMoreFlag:true,
			searchbarForm:{},
			
			regionOptions:regionData,           // 省市区信息
			cascaderProps:{
                value: 'code',
                label:'name',
                children:'cell'
            },
			searchArr:[],		// 前端的查询条件，里面的field对应前端的字段
			rules:[]			// 后端的查询条件，里面的field对应后端的字段
		}
	},
	// computed:{
	// 	key(){
	// 		return this.$route.name!=undefined?this.$route.name + new Date():this.$route + new Date();
	// 	}
	// },
	created(){
		// this.init();
	},
	methods: {
		// 初始化属性
		init(query){
			let _this = this;
			this.searchItems.normal && this.searchItems.normal.forEach(item=>{
				if(item.type=='radio' || item.type=='checkbox'){
					_this.$set(_this.searchbarForm,item.field,'')
				}else if(item.type==='region'){
					_this.$set(_this.searchbarForm,item.field,[])
				}else{
					_this.$set(_this.searchbarForm,item.field,item.default || null)
				}
			});
			this.searchItems.more && this.searchItems.more.forEach(item=>{
				if(item.type=='radio' || item.type=='checkbox'){
					_this.$set(_this.searchbarForm,item.field,'')
				}else if(item.type==='region'){
					_this.$set(_this.searchbarForm,item.field,[])
				}else{
					_this.$set(_this.searchbarForm,item.field,item.default || null)
				}
			});
			let setArr = [].concat(this.searchItems.normal).concat(this.searchItems.more)
			if(Object.keys(query).length>0){
				Object.keys(query).forEach(key => {
					if(_this.searchbarForm[key] !== undefined){
						if(setArr.length>0){
							let filterArr = setArr.filter(it=>{
								return it.field===key;
							})
							if(filterArr.length>0){		// 说明该属性是存在于搜索栏
								let filter = filterArr[0];
								if(filter.type==='select' || filter.type==='radio' || filter.type==='checkbox'){
									// 若是这些类型，则需要判断是否存在下拉框或者是否该值在options里面
									let val = decodeURIComponent(query[key]);
									let selectedOption = filter.options.filter(it=>{
										return it.value === val
									})
									if(selectedOption.length>0){
										_this.$set(_this.searchbarForm,key,decodeURIComponent(query[key]))
									}else{
										// 说明不在options里面
										_this.$set(_this.searchbarForm,key,'')
									}
								}else if(filter.type==='daterange'){
									let tempVal = decodeURIComponent(query[key]);
									let tempValArr = tempVal.split(',');
									if(tempValArr.length==2){
										_this.$set(_this.searchbarForm,key,[
											Tool.formatDate(tempValArr[0],filter.valueFormat),
											Tool.formatDate(tempValArr[1],filter.valueFormat)
										])
									}else{
										_this.$set(_this.searchbarForm,key,null)
									}
									
								}else if(filter.type==='region'){
									let tempVal = decodeURIComponent(query[key]);
									let resVal = [];
									if(tempVal && /^(\d{6}),(\d{6}),(\d{6})$/g.test(tempVal)){
										resVal = tempVal.split(',')
									}
									_this.$set(_this.searchbarForm,key,resVal);
								}else{
									_this.$set(_this.searchbarForm,key,decodeURIComponent(query[key]))
								}
								
							}else{
								// 说明设置的属性不存在于搜索栏
								// _this.$set(_this.searchbarForm,key,decodeURIComponent(query[key]))
							}
						}
					}
				});
				_this.showMoreFlag = false;
			}
			
		},
		get(){
			let rules=[],
				searchArr = [];
			this.searchItems.normal && this.searchItems.normal.forEach(item=>{
				let data = this.searchbarForm[item.field] || null;
				let selectedOption;
				if(item.type==='select' && item.postdifferent){
					let selectPostData = data?data:'';
					selectedOption = item.options.filter(it=>{
						return it.value === selectPostData
					})
				}else if(item.type==='daterange'){
					data = (data && data[0])?data:null;		// 用来解决表单重置之后时间间隔组件返回的数据是[undefined]
				}else if(item.type==='region'){
					data = (data && data.length>0)?data.join(','):null;		// 省市区[330000,330700,330781],需要转成字符串"330000,330700,330781"
				}
				if(data){
					if(typeof data ==='string'){
						data = data.trim();
						data = data.replace(/\s/g,'');
					}
					if(item.type==='select' && item.postdifferent){
						rules.push({field: item.dbfield, op: selectedOption[0].dboper, data: selectedOption[0].postData});
						searchArr.push({name:item.field,value:data})
					}else{
						rules.push({field: item.dbfield, op: item.dboper, data: data});
						searchArr.push({name:item.field,value:data})
					}
				}
			});
			this.searchItems.more && this.searchItems.more.forEach(item=>{
				let data = this.searchbarForm[item.field] || null;
				let selectedOption;
				if(item.type==='select' && item.postdifferent){
					let selectPostData = data?data:'';
					selectedOption = item.options.filter(it=>{
						return it.value === selectPostData
					})
				}else if(item.type==='daterange'){
					data = (data && data[0])?data:null;		// 用来解决表单重置之后时间间隔组件返回的数据是[undefined]
				}else if(item.type==='region'){
					data = (data && data.length>0)?data.join(','):null;		// 省市区[330000,330700,330781],需要转成字符串"330000,330700,330781"
				}
				if(data){
					if(typeof data ==='string'){
						data = data.trim();
						data = data.replace(/\s/g,'');
					}
					if(item.type==='select' && item.postdifferent){
						rules.push({field: item.dbfield, op: selectedOption[0].dboper, data: selectedOption[0].postData});
						searchArr.push({name:item.field,value:data})
					}else{
						rules.push({field: item.dbfield, op: item.dboper, data: data});
						searchArr.push({name:item.field,value:data})
					}
				}
			});

			this.$set(this,'searchArr',searchArr);			// 前端查询条件数据
			this.$set(this,'rules',rules);					// 后端查询条件数据
			
			let searchObj= {
				"groupOp": "AND",
				"rules": rules
			}
			
			return searchObj;
		},
		
		// 获取url的search变量
		getLocationObj(){
			let str=window.location.href,
				i = str.lastIndexOf('?');
			if(i<0){
				return str;
			}
			let obj = str.substr(i+1).split('&'),
				rtrnObj = {};
			for(let i=0;i < obj.length; i++){
				let temp = obj[i].split("=");
				rtrnObj[temp[0]] = decodeURIComponent(temp[1]);
			}
			if(this.pagination){			// 存放分页数据
				rtrnObj['currPage'] = parseInt(this.pagination.page) || 1;
				rtrnObj['pageSize'] = parseInt(this.pagination.limit) || 20;
			}
			return rtrnObj;
		},

		// 设置url的search变量
		getLocationStr(arr){
			let str=window.location.href,
				i = str.lastIndexOf('?');
			let newStr = null;
			if(i>=0){
				newStr = str.substr(0,i);
			}else{
				newStr = str;
			}
			if(arr.length>0){
				newStr = newStr+'?';
				arr.forEach(item=>{
					newStr+=item.name+'='+encodeURIComponent(item.value)+'&'
				})
				newStr = newStr.substr(0,newStr.length-1);
			}
			if(this.pagination){			// 存放分页数据
				if(arr.length>0){
					newStr = newStr+'&currPage'+'='+(parseInt(this.pagination.page) || 1);
					newStr = newStr+'&pageSize'+'='+(parseInt(this.pagination.limit) || 20);
				}else{
					newStr = newStr+'?';
					newStr = newStr+'currPage'+'='+(parseInt(this.pagination.page) || 1);
					newStr = newStr+'&pageSize'+'='+(parseInt(this.pagination.limit) || 20);
				}
			}
			return newStr;
		},

		/**
		 * 搜索操作，需要传值使外层的currentPage设置为1，默认为是需要重置分页显示为第一页
		 * 
		 * notResetCurrentPage为true时表示不重置currentPage，用于外层分页方法调用
		 */
		searchHandle(notResetCurrentPage){
			let postData = this.get();
			if(!notResetCurrentPage){		// 重置设置为将页面设置为第一页
				this.pagination.page = 1;
			}
			let locationStr = this.getLocationStr(this.searchArr);
			window.history.pushState('','',locationStr);
			
			if(notResetCurrentPage){
				this.$emit('search',{resetCurrentPage:false,searchData:postData});
			}else{
				this.$emit('search',{resetCurrentPage:true,searchData:postData});
			}
		},

		// 清空搜索操作
		clearSearchHandle(){
			if(this.$refs.searchbarForm){
				this.$refs['searchbarForm'].resetFields();
			}
			this.$nextTick(() => {
				this.searchHandle();
			});
		},

		// 显示更多查询
		showMoreHandle(){
			this.showMoreFlag = !this.showMoreFlag;
			this.$emit('resizeSearchbar');
		}
	}
}
</script>

<style scoped>
.show-more-btn{
	position: relative;
	font-size:12px;
	color:#2288d0;
	text-decoration: none;
	margin:0 8px 0 5px;
}
.show-more-btn:hover{
	text-decoration:underline;
}
.triangle-down:after{
	content:'';
	position: relative;
	top:1px;
	display: inline-block;
	margin-left:5px;
    border: 4px solid transparent;
    border-top-color: #2288d0;
}
.triangle-up:after{
	content:'';
	position: relative;
	top:-3px;
	display: inline-block;
	margin-left:5px;
	margin-top:-5px;
    border: 4px solid transparent;
    border-bottom-color: #2288d0;
}
</style>